import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '../store'

import Home from '../views/Home.vue'
import Login from '../views/Login.vue'
import City from '../views/City.vue'
import FilmDetail from '../views/Film/_id.vue'
import FilmList from '../views/Home/Films.vue'
import CinemaDetail from '../views/Cinema/_id.vue'
import CinemaList from '../views/Home/Cinemas.vue'
import Center from '../views/Home/Center.vue'
import Balance from '../views/User/Balance.vue'
import Card from '../views/User/Card.vue'

Vue.use(VueRouter)

const router = new VueRouter({
  routes: [
    {
      path: '/',
      component: Home,
      children: [
        {
          path: 'films',
          component: FilmList,
          meta: {
            tabIndex: 0
          }
        },
        {
          path: 'cinemas',
          component: CinemaList,
          meta: {
            tabIndex: 1
          }
        },
        {
          path: 'center',
          component: Center,
          meta: {
            tabIndex: 2
          }
        },
        {
          path: '',
          redirect: '/films'
        }
      ]
    },
    {
      path: '/city',
      name: 'city',
      component: City
    },
    {
      path: '/login',
      component: Login
    },
    {
      path: '/film/:filmId',
      component: FilmDetail
    },
    {
      path: '/cinema/:cinemaId/film',
      component: CinemaDetail
    },
    {
      path: '/user/balance',
      component: Balance,
      meta: {
        needLogin: true
      }
    },
    {
      path: '/user/card',
      component: Card,
      meta: {
        needLogin: true
      }
    }
  ]
})

router.beforeEach((to, from, next) => {
  if (to.meta.needLogin && !store.state.userInfo) {
    next('/login')
  } else {
    if (!store.state.city && to.name !== 'city') {
      next('/city')
    } else {
      next()
    }
  }
})

export default router
